package com.litree.service.controller;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.litree.service.model.User;
import com.litree.service.services.impl.TestUsrService;


@Controller
public class UsrController {
	@Autowired
	private TestUsrService tuserService;
	
	@RequestMapping(method=RequestMethod.GET, value="/list")
	public void getUsrList(HttpServletResponse response) {
		List<String> ss = tuserService.getUsrList();
		
		
		JSONArray jsonArray = new JSONArray();
		
		try {
			for (String s : ss){
				JSONObject json = new JSONObject();
				json.put("name", s);
				jsonArray.add(json);
			}
			response.getWriter().write(jsonArray.toString());
			
		}catch(Exception e){
			System.out.println(e);
		}
		
	}
	
	@RequestMapping(method=RequestMethod.GET, value="/users/list")
	public void getUsersList(HttpServletResponse response){
		List<User> users = tuserService.getUsersList();
		
		JSONArray jsonArray = new JSONArray();
		try {
			for (User user: users){
				final JSONObject json = new JSONObject();
				json.put("age",user.getAge());
				jsonArray.add(json);
			}
			response.getWriter().write(jsonArray.toString());
		}catch(Exception e){
			
		}
	}
	
	@RequestMapping(method=RequestMethod.POST, value="/users/list",consumes = "application/json")
	public void updateUsr(@RequestBody String bodyStr, HttpServletResponse response){
		final User user = JSON.parseObject(bodyStr,User.class);
		if (user != null){
			tuserService.updateUsr(user);
		}
		try {
		   response.getWriter().write("yeah!");
		}catch(Exception e){
			
		}
	}
	
}
